<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use DB;
use Hash;

class checkOldPasswordRule implements Rule
{
    protected $table;
    protected $password_column;
    protected $user_id;

    /**
     * Create a new rule instance.
     * @param $table
     * @param $password_column
     * @param $user_id
     */
    public function __construct($table, $password_column, $user_id)
    {
        $this->table = $table;
        $this->password_column = $password_column;
        $this->user_id = $user_id;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $user = DB::table($this->table)->where('id', '=', $this->user_id)->first();

        if (empty($user)) {
            return false;
        }

        return Hash::check($value, $user->{$this->password_column});
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return '原始密码验证失败';
    }
}
